package org.hydrakyoufeng.stuplatform.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public final class JWTUtils {

    /**
     * 密钥
     */
    private String password = "12345678abc";

    @Autowired
    private DesUtils desUtils;

    /**
     * 创建一个Token对象，保存一些基本信息
     * @param id 主键
     * @param type 用户类型
     * @return
     */
    public Map<String,Object> createTokenMap(Integer id, String type) {
        Map<String,Object> tokenMap = new HashMap<>();
        tokenMap.put("id",id);
        tokenMap.put("type",type);
        tokenMap.put("timestamp",new Date().getTime());
        return tokenMap;
    }

    /**
     * 生成将Token存到缓存中的KEY
     * @param tokenMap
     * @param ip
     * @return
     */
    public String generateCacheKey(Map<String,Object> tokenMap,String ip) {
        StringBuilder sb = new StringBuilder();
        sb.append(tokenMap.get("id"));
        sb.append(tokenMap.get("type"));
        sb.append(tokenMap.get("timestamp"));
        sb.append(ip);
        return sb.toString();
    }

    /**
     * 获取客户端的ip地址
     * @param request
     * @return
     */
    public String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 序列化tokenMap并加密
     * @param tokenMap
     * @return
     */
    public String encodeTokenMap(Map<String,Object> tokenMap) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(tokenMap);
        // 加密
        return desUtils.encodeDESAsBase64(jsonStr, password);
    }


    /**
     * 将Token字符串反序列化为Map
     * @param tokenStr
     * @return
     * @throws Exception
     */
    public Map<String,Object> decodeTokenStr(String tokenStr) throws Exception {
        // 解密
        tokenStr = desUtils.decodeDESAsBase64(tokenStr, password);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> tokenMap = objectMapper.readValue(tokenStr, Map.class);
        return tokenMap;
    }
}
